package cn.stylefeng.guns.modular.manager.controller;

import cn.janaker.paysdk.model.result.IRefundResult;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.module.OrderStatus;
import cn.stylefeng.guns.modular.manager.entity.*;
import cn.stylefeng.guns.modular.manager.model.params.FlowCouponParam;
import cn.stylefeng.guns.modular.manager.model.params.FlowGoodsParam;
import cn.stylefeng.guns.modular.manager.model.params.FlowOrderGoodsParam;
import cn.stylefeng.guns.modular.manager.model.params.FlowOrderParam;
import cn.stylefeng.guns.modular.manager.model.result.FlowOrderGoodsResult;
import cn.stylefeng.guns.modular.manager.model.result.FlowOrderResult;
import cn.stylefeng.guns.modular.manager.service.*;
import cn.stylefeng.guns.modular.mobile.base.MobileWXBaseController;
import cn.stylefeng.guns.modular.paytest.service.PayService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.FlowDeptPhones;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.FlowDeptPhonesService;
import cn.stylefeng.guns.utils.*;
import cn.stylefeng.guns.utils.weixin.WxTemplateUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;


/**
 * 订单记录控制器
 *
 * @author yumker
 * @Date 2021-01-07 17:22:24
 */
@Controller
@RequestMapping("/flowOrder")
public class FlowOrderController extends BaseController {

    private String PREFIX = "/manager/flowOrder";
    private String PREFIX1 = "/manager/flowLowerLevelOrder";

    @Autowired
    private FlowOrderService flowOrderService;
    @Autowired
    private FlowGoodsService flowGoodsService;
    @Autowired
    private FlowCouponService flowCouponService;
    @Autowired
    private FlowPayInfoService flowPayInfoService;
    @Autowired
    private PayService payService;
    @Autowired
    private FlowWxMemberService flowWxMemberService;
    @Autowired
    private MobileWXBaseController mobileWXBaseController;
    @Autowired
    private FlowCommissionManagementService flowCommissionManagementService;
    //发送生成订单的短信
    @Autowired
    protected FlowDeptPhonesService flowDeptPhonesService;
    @Autowired
    protected DeptService deptService;
    @Autowired
    private FlowStoreCityService flowStoreCityService;

    /**
     * 跳转到主页面
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/flowOrder.html";
    }

    @RequestMapping("/flowLowerLeverOrder")
    public String flowLowerLeverOrder() {
        return PREFIX1 + "/flowLowerLevelOrder.html";
    }


    /**
     * 新增页面
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/flowOrder_add.html";
    }

    /**
     * 编辑页面
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/flowOrder_edit.html";
    }

    /**
     * 新增接口
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(FlowOrderParam flowOrderParam) {
        this.flowOrderService.add(flowOrderParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(FlowOrderParam flowOrderParam) {
        //查询旧的订单
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",flowOrderParam.getOrderId());
        flowOrderQueryWrapper.last("limit 1");
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        try{
            if(flowOrderParam.getKilometerNote() != null && !flowOrderParam.getKilometerNote().equals("")){
                flowOrderParam.setKilometerNote(Escape.unescape(flowOrderParam.getKilometerNote()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        double payMoneys = 0;
        double youhui = 0;
      
        payMoneys += flowOrderParam.getMoneys().doubleValue();
        payMoneys += flowOrderParam.getSettlementMoneys().doubleValue();

        //查询订单的物品
        QueryWrapper<FlowOrderGoods> flowOrderGoodsQueryWrapper = new QueryWrapper<>();
        flowOrderGoodsQueryWrapper.eq("order_id",flowOrderParam.getOrderId());
        List<FlowOrderGoods> flowOrderGoods = flowOrderGoodsService.list(flowOrderGoodsQueryWrapper);
        List<FlowOrderGoods> goods = new ArrayList<>();

        //商品名称#商品id#商品数量#商品价格,
        if(flowOrderParam.getCGoods() != null && !flowOrderParam.getCGoods().equals("")){
            flowOrderParam.setCGoods(Escape.unescape(flowOrderParam.getCGoods()));
            String []cgArr = flowOrderParam.getCGoods().split(",");
            for (int i = 0;i<cgArr.length;i++){
                String[]arr = cgArr[i].split("#");
                if(arr.length == 4){
                    FlowOrderGoods flowOrderGoods1 = new FlowOrderGoods();
                    flowOrderGoods1.setGoodsName(arr[0]);
                    flowOrderGoods1.setGoodsId(Long.parseLong(arr[1]));
                    flowOrderGoods1.setGoodsCount(Integer.parseInt(arr[2]));
                    flowOrderGoods1.setGoodsPrice(new BigDecimal(arr[3]));
                    flowOrderGoods1.setOrderId(flowOrderParam.getOrderId());
                    flowOrderGoods1.setUpdateTime(new Date());
                    flowOrderGoods1.setCreateTime(new Date());
                    goods.add(flowOrderGoods1);
                }
            }
        }

        //全部删除，再添加
        for (int i = 0;i<flowOrderGoods.size();i++){
            QueryWrapper<FlowOrderGoods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("order_goods_id",flowOrderGoods.get(i).getOrderGoodsId());
            flowOrderGoodsService.remove(goodsQueryWrapper);
        }
        //添加
        for (int i = 0;i<goods.size();i++){
            payMoneys += goods.get(i).getGoodsCount() * goods.get(i).getGoodsPrice().doubleValue();
            flowOrderGoodsService.save(goods.get(i));
        }

        if(flowOrderParam.getPayMoneys() != null && flowOrderParam.getPayMoneys().doubleValue() >= 0.01d){
            payMoneys = flowOrderParam.getPayMoneys().doubleValue();
        }



        if(flowOrder.getOrderStatus().intValue() != OrderStatus.OrderServiceSuccess && flowOrder.getOrderStatus().intValue() != OrderStatus.OrderCompletion){
            //查询优惠卷
            if(flowOrderParam.getCouponId() != null && flowOrderParam.getCouponId() > 0){
                //查询优惠
                QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
                flowCouponQueryWrapper.eq("coupon_id",flowOrderParam.getCouponId());
                FlowCoupon flowCoupon = flowCouponService.getOne(flowCouponQueryWrapper);
                //查询订单明细，是否是选择的优惠卷
                QueryWrapper<FlowOrderDis> flowOrderDisQueryWrapper = new QueryWrapper<>();
                flowOrderDisQueryWrapper.eq("order_id",flowOrderParam.getOrderId());
                flowOrderDisQueryWrapper.last("limit 1");
                FlowOrderDis flowOrderDis = flowOrderDisService.getOne(flowOrderDisQueryWrapper);

                if(flowCoupon != null){
                    if(flowOrderDis == null){
                        if(flowCoupon.getOnprice().doubleValue() >= payMoneys){
                            return ResponseData.error("抱歉，该优惠卷满"+flowCoupon.getOnprice()+"使用");
                        }
                        if(flowCoupon.getIsUsed().intValue() == 1){
                            return ResponseData.error("该卷已使用");
                        }
                        //判断是否过期
                        if(flowCoupon.getOutDay().intValue() > 0 && flowCoupon.getEndTime().compareTo(new Date()) < 0){
                            return ResponseData.error("该卷已过期");
                        }
                        if(payMoneys < flowCoupon.getMoneys().doubleValue()){
                            return ResponseData.error("订单金额小于优惠卷金额");
                        }
                        //添加
                        flowOrderDis = new FlowOrderDis();
                        flowOrderDis.setCouponId(flowCoupon.getCouponId());
                        flowOrderDis.setDisMoneys(flowCoupon.getMoneys());
                        flowOrderDis.setNote(flowCoupon.getCouponTitle());
                        flowOrderDis.setOrderId(flowOrderParam.getOrderId());
                        youhui = flowOrderDis.getDisMoneys().doubleValue();
                        flowOrderDisService.save(flowOrderDis);
                        //更新优惠卷
                        flowCoupon.setIsUsed(1);
                        flowCoupon.setUseTime(new Date());
                        flowCouponService.updateById(flowCoupon);
                    }else {
                        youhui = flowOrderDis.getDisMoneys().doubleValue();
                    }
                }
            }
            //计算楼层费用
            if(flowOrderParam.getBegElevatorPrice() != null){
                payMoneys += flowOrderParam.getBegElevatorPrice().doubleValue();
            }
            if(flowOrderParam.getEndElevatorPrice() != null){
                payMoneys += flowOrderParam.getEndElevatorPrice().doubleValue();
            }
            if(flowOrderParam.getPayMoneys() == null || flowOrderParam.getPayMoneys().doubleValue() < 0.01d){
                flowOrderParam.setPayMoneys(new BigDecimal(payMoneys));
            }

            if(flowOrderParam.getAllPayMoneys() == null || flowOrderParam.getAllPayMoneys().doubleValue() < 0.01d){
                flowOrderParam.setAllPayMoneys(new BigDecimal(payMoneys - youhui));
            }

        }

        this.flowOrderService.update(flowOrderParam);
        //更新别的数据

        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(FlowOrderParam flowOrderParam) {
        this.flowOrderService.delete(flowOrderParam);
        return ResponseData.success();
    }
    @Autowired
    private FlowOrderLogService flowOrderLogService;
    @Autowired
    private FlowServiceService flowServiceService;
    @Autowired
    private FlowServiceTypeService flowServiceTypeService;
    @Autowired
    private FlowOrderGoodsService flowOrderGoodsService;
    @Autowired
    private FlowOrderDisService flowOrderDisService;
    @Autowired
    private FlowZfbMemberService flowZfbMemberService;
    @Autowired
    private FlowBdMemberService flowBdMemberService;
    /**
     * 查看详情接口
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(FlowOrderParam flowOrderParam) {
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        //查询订单的具体地理位置
        QueryWrapper<FlowOrderLog> flowOrderLogQueryWrapper = new QueryWrapper<>();
        flowOrderLogQueryWrapper.eq("order_id",detail.getOrderId());
        flowOrderLogQueryWrapper.last("limit 1");
        FlowOrderLog flowOrderLog = flowOrderLogService.getOne(flowOrderLogQueryWrapper);
        if(flowOrderLog != null){
            detail.setBegAddress(flowOrderLog.getBegComAddress() + " " + flowOrderLog.getBegDetail() +" " + flowOrderLog.getBegElevator());
            detail.setEndAddress(flowOrderLog.getEndComAddress() + " " + flowOrderLog.getEndDetail() +" " + flowOrderLog.getEndElevator());
        }

        //查询订单的服务类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",detail.getOrderType());
        flowServiceQueryWrapper.last("limit 1");
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        if(flowService != null){
            detail.setOrderTypeName(flowService.getServiceName());
        }

        //查询同城订单的服务类型
        if(detail.getOrderType().longValue() == 1){
            QueryWrapper<FlowServiceType> flowServiceTypeQueryWrapper = new QueryWrapper<>();
            flowServiceTypeQueryWrapper.eq("service_type_id",detail.getServiceType());
            flowServiceTypeQueryWrapper.last("limit 1");
            FlowServiceType flowServiceType = flowServiceTypeService.getOne(flowServiceTypeQueryWrapper);
            if(flowServiceType != null){
                detail.setServiceName(flowServiceType.getTypeName());
            }
        }

        //查询订单的物品
        FlowOrderGoodsParam flowOrderGoodsParam = new FlowOrderGoodsParam();
        flowOrderGoodsParam.setOrderId(detail.getOrderId());
        List<FlowOrderGoodsResult> flowOrderGoods = flowOrderGoodsService.selectOrderDisList(flowOrderGoodsParam);
        detail.setFlowOrderGoods(flowOrderGoods);
        //查询订单使用的优惠卷
        QueryWrapper<FlowOrderDis> flowOrderDisQueryWrapper = new QueryWrapper<>();
        flowOrderDisQueryWrapper.eq("order_id",detail.getOrderId());
        flowOrderDisQueryWrapper.last("limit 1");
        FlowOrderDis flowOrderDis = flowOrderDisService.getOne(flowOrderDisQueryWrapper);
        detail.setFlowOrderDis(flowOrderDis);
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(FlowOrderParam flowOrderParam) {
        //查询是否是服务网点
        LoginUser user = LoginContextHolder.getContext().getUser();
        if(!user.getAccount().equals("admin")){
            flowOrderParam.setDeptId(user.getDeptId());
        }
        LayuiPageInfo layuiPageInfo = this.flowOrderService.findPageBySpec(flowOrderParam);
        //这里查询账户电话
        //如果是百度，或者是支付宝
        List<Long> bdIds = new ArrayList<>();
        List<Long> zfbIds = new ArrayList<>();
        List<Long> wxIds = new ArrayList<>();
        List<FlowOrderResult> flowOrders = layuiPageInfo.getData();
        for (int i = 0;i<flowOrders.size();i++){
            if(flowOrders.get(i).getZfbMemberId() != null && flowOrders.get(i).getZfbMemberId().longValue() > 0){
                zfbIds.add(flowOrders.get(i).getZfbMemberId());
            }
            if(flowOrders.get(i).getBdMemberId() != null && flowOrders.get(i).getBdMemberId().longValue() > 0){
                bdIds.add(flowOrders.get(i).getBdMemberId());
            }
            if(flowOrders.get(i).getWxMemberId() != null && flowOrders.get(i).getWxMemberId().longValue() > 0){
                wxIds.add(flowOrders.get(i).getWxMemberId());
            }
        }
        if(zfbIds.size() != 0){
            //查询
            QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
            flowZfbMemberQueryWrapper.in("member_id",zfbIds);
            List<FlowZfbMember> flowZfbMembers = flowZfbMemberService.list(flowZfbMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowZfbMembers.size();j++){
                    if(flowOrders.get(i).getZfbMemberId() != null && flowOrders.get(i).getZfbMemberId().longValue() == flowZfbMembers.get(j).getMemberId().longValue()){
                        flowOrders.get(i).setMemberAccount(flowZfbMembers.get(j).getAccount());
                    }
                }
            }
        }

        if(bdIds.size() != 0){
            //查询
            QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
            flowBdMemberQueryWrapper.in("member_id",bdIds);
            List<FlowBdMember> flowBdMembers = flowBdMemberService.list(flowBdMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowBdMembers.size();j++){
                    if(flowOrders.get(i).getBdMemberId() != null && flowOrders.get(i).getBdMemberId().longValue() == flowBdMembers.get(j).getMemberId().longValue()){
                        flowOrders.get(i).setMemberAccount(flowBdMembers.get(j).getAccount());
                    }
                }
            }
        }

        if(wxIds.size() != 0){
            //查询
            QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
            flowWxMemberQueryWrapper.in("member_id",wxIds);
            List<FlowWxMember> flowWxMembers = flowWxMemberService.list(flowWxMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowWxMembers.size();j++){
                    if(flowOrders.get(i).getWxMemberId() != null && flowOrders.get(i).getWxMemberId().longValue() == flowWxMembers.get(j).getMemberId().longValue()){
                        flowOrders.get(i).setMemberAccount(flowWxMembers.get(j).getAccount());
                    }
                }
            }
        }
        return layuiPageInfo;
    }

    /**
     * 查询佣金列表
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @ResponseBody
    @RequestMapping("/lowerLevelList")
    public LayuiPageInfo lowerLevelList(FlowOrderParam flowOrderParam) {
        //查询是否是服务网点
        LoginUser user = LoginContextHolder.getContext().getUser();
        if(!user.getAccount().equals("admin")){
            flowOrderParam.setDeptId(user.getDeptId());
        }
        flowOrderParam.setSuperUserId(1l);
        LayuiPageInfo layuiPageInfo = this.flowOrderService.findPageBySpec(flowOrderParam);
        //这里查询账户电话
        //如果是百度，或者是支付宝
        List<Long> bdIds = new ArrayList<>();
        List<Long> zfbIds = new ArrayList<>();
        List<Long> wxIds = new ArrayList<>();
        List<FlowOrderResult> flowOrders = layuiPageInfo.getData();
        for (int i = 0;i<flowOrders.size();i++){
            if(flowOrders.get(i).getZfbMemberId() != null && flowOrders.get(i).getZfbMemberId().longValue() > 0){
                zfbIds.add(flowOrders.get(i).getZfbMemberId());
            }
            if(flowOrders.get(i).getBdMemberId() != null && flowOrders.get(i).getBdMemberId().longValue() > 0){
                bdIds.add(flowOrders.get(i).getBdMemberId());
            }
            if(flowOrders.get(i).getWxMemberId() != null && flowOrders.get(i).getWxMemberId().longValue() > 0){
                wxIds.add(flowOrders.get(i).getWxMemberId());
            }
        }
        if(zfbIds.size() != 0){
            //查询
            QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
            flowZfbMemberQueryWrapper.in("member_id",zfbIds);
            List<FlowZfbMember> flowZfbMembers = flowZfbMemberService.list(flowZfbMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowZfbMembers.size();j++){
                    if(flowOrders.get(i).getZfbMemberId() != null && flowOrders.get(i).getZfbMemberId().longValue() == flowZfbMembers.get(j).getMemberId().longValue()){

                            flowOrders.get(i).setMemberAccount(flowZfbMembers.get(j).getAccount());


                    }
                }
            }
        }

        if(bdIds.size() != 0){
            //查询
            QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
            flowBdMemberQueryWrapper.in("member_id",bdIds);
            List<FlowBdMember> flowBdMembers = flowBdMemberService.list(flowBdMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowBdMembers.size();j++){
                    if(flowOrders.get(i).getBdMemberId() != null && flowOrders.get(i).getBdMemberId().longValue() == flowBdMembers.get(j).getMemberId().longValue()){

                            flowOrders.get(i).setMemberAccount(flowBdMembers.get(j).getAccount());


                    }
                }
            }
        }

        if(wxIds.size() != 0){
            //查询
            QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
            flowWxMemberQueryWrapper.in("member_id",wxIds);
            List<FlowWxMember> flowWxMembers = flowWxMemberService.list(flowWxMemberQueryWrapper);
            for (int i = 0;i<flowOrders.size();i++){
                for (int j = 0;j<flowWxMembers.size();j++){
                    if(flowOrders.get(i).getWxMemberId() != null && flowOrders.get(i).getWxMemberId().longValue() == flowWxMembers.get(j).getMemberId().longValue()){

                            flowOrders.get(i).setMemberAccount(flowWxMembers.get(j).getAccount());


                    }
                }
            }
        }
        return layuiPageInfo;
    }

    /**
     * 跳转到主页面
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @RequestMapping("flowGoods")
    public String flowGoods() {
        return PREFIX + "/flowGoods.html";
    }

    @RequestMapping("flowCoupon")
    public String flowCoupon() {
        return PREFIX + "/flowCoupon.html";
    }

    /**
     * 查询列表
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @ResponseBody
    @RequestMapping("/flowGoodsList")
    public LayuiPageInfo flowGoodsList(FlowGoodsParam flowGoodsParam) {
        //查询价格
        return this.flowGoodsService.customGoodsPageList(flowGoodsParam);
    }

    /**
     * 查询列表
     *
     * @author yumker
     * @Date 2021-01-07
     */
    @ResponseBody
    @RequestMapping("/flowCouponList")
    public LayuiPageInfo flowCouponList(FlowCouponParam flowCouponParam) {
        flowCouponParam.setIsUsed(0);
        return this.flowCouponService.findPageBySpec(flowCouponParam);
    }

    //订单确认
    @ResponseBody
    @RequestMapping("/confirmOrder")
    public ResponseData confirmOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(detail.getOrderStatus() != OrderStatus.OrderWaitConfirm){
            return ResponseData.error("该订单已被处理");
        }
        int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderDealing,OrderStatus.OrderWaitConfirm);
        if(result > 0){
            //更新订单的操作人员
            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
            LoginUser user = LoginContextHolder.getContext().getUser();
            flowOrderParam1.setUpdateUser(user.getId());
            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
            flowOrderParam1.setDepositPay(0l);
            flowOrderService.update(flowOrderParam1);
            //取消订单短信
            try{
                QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
                flowServiceQueryWrapper.eq("service_id",detail.getOrderType());
                FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
                //发送支付成功短信
                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
                    flowZfbMemberQueryWrapper.last("limit 1");
                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
                    if(flowZfbMember != null){
                        AliyuncsUtil.sendSmsOrder(3,flowZfbMember.getAccount(),flowService.getServiceName());
                    }
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
                    flowBdMemberQueryWrapper.last("limit 1");
                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
                    if(flowBdMember != null){
                        AliyuncsUtil.sendSmsOrder(3,flowBdMember.getAccount(),flowService.getServiceName());
                    }
                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
                    flowWxMemberQueryWrapper.last("limit 1");
                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
                    if(flowWxMember != null){
                        AliyuncsUtil.sendSms(3,flowWxMember.getAccount(),flowService.getServiceName());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }else {
            return ResponseData.error("操作失败");
        }
    }

    //设置为可支付
    @ResponseBody
    @RequestMapping("/canPayOrder")
    public ResponseData canPayOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(detail.getOrderStatus() != OrderStatus.OrderDealing){
            return ResponseData.error("该订单已被处理");
        }
        int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderWaitPay,OrderStatus.OrderDealing);
        if(result > 0){
            //更新订单的操作人员
            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
            LoginUser user = LoginContextHolder.getContext().getUser();
            flowOrderParam1.setUpdateUser(user.getId());
            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
            flowOrderService.update(flowOrderParam);
            try{
                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
                    flowZfbMemberQueryWrapper.last("limit 1");
                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
                    if(flowZfbMember != null){
                        AliyuncsUtil.sendSms(4,flowZfbMember.getAccount(),"","");
                    }
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
                    flowBdMemberQueryWrapper.last("limit 1");
                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
                    if(flowBdMember != null){
                        AliyuncsUtil.sendSms(4,flowBdMember.getAccount(),"","");
                    }
                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
                    flowWxMemberQueryWrapper.last("limit 1");
                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
                    if(flowWxMember != null){
                        AliyuncsUtil.sendSms(4,flowWxMember.getAccount(),"","");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }else {
            return ResponseData.error("操作失败");
        }
    }

    //设置为已支付
    @ResponseBody
    @RequestMapping("/payOrder")
    public ResponseData payOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(detail.getOrderStatus() != OrderStatus.OrderWaitPay){
            return ResponseData.error("该订单已被处理");
        }
        int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderWaitService,OrderStatus.OrderWaitPay);
        if(result > 0){
            //更新订单的操作人员
            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
            LoginUser user = LoginContextHolder.getContext().getUser();
            flowOrderParam1.setUpdateUser(user.getId());
            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
            flowOrderService.update(flowOrderParam);
            //发送支付成功短信
            try{
                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
                    flowZfbMemberQueryWrapper.last("limit 1");
                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
                    if(flowZfbMember != null){
                        AliyuncsUtil.sendSms(2,flowZfbMember.getAccount(),"","");
                    }
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
                    flowBdMemberQueryWrapper.last("limit 1");
                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
                    if(flowBdMember != null){
                        AliyuncsUtil.sendSms(2,flowBdMember.getAccount(),"","");
                    }
                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
                    flowWxMemberQueryWrapper.last("limit 1");
                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
                    if(flowWxMember != null){
                        AliyuncsUtil.sendSms(2,flowWxMember.getAccount(),"","");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }else {
            return ResponseData.error("操作失败");
        }
    }

    //取消订单
    @ResponseBody
    @RequestMapping("/canselOrder")
    public ResponseData canselOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        //判断可不可以退款
        //尾款退款

        if(detail.getPayStatus() == OrderStatus.IsPay){

            //查询支付的code
            try{
                QueryWrapper<FlowPayInfo> flowPayInfoQueryWrapper = new QueryWrapper<>();
                flowPayInfoQueryWrapper.eq("order_id",detail.getOrderId());
                flowPayInfoQueryWrapper.eq("pay_status",OrderStatus.IsPay);
                flowPayInfoQueryWrapper.eq("pay_code",detail.getPayCode());

                flowPayInfoQueryWrapper.orderByDesc("pay_info_id");

                FlowPayInfo flowPayInfo = flowPayInfoService.getOne(flowPayInfoQueryWrapper);
                if(flowPayInfo != null){
                    System.out.println("tttttttttttt1"+flowPayInfo.getMoneys().intValue());
                    if(flowPayInfo.getPayType().intValue() == 0){
                        //支付宝支付
                        //已经支付
                        AlipayClient client = new AliUtil().getAlipayClient();
                        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
                        refundModel.setOutTradeNo(flowPayInfo.getPayCode());
                        refundModel.setTradeNo(flowPayInfo.getTradeNo());
                        refundModel.setRefundAmount(String .format("%.2f",flowPayInfo.getMoneys().doubleValue()));
                        request.setBizModel(refundModel);
                        AlipayTradeRefundResponse res = client.certificateExecute(request); //发送退款请求,获得退款结果
                        if(res.isSuccess()){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }else if(flowPayInfo.getPayType().intValue() == 1){
                        flowPayInfo.setRefundCode(CommonUtil.getRanDomStringId());
                        Map<String,Object> res = BdUtil.orderRefund(flowPayInfo.getUserId(),flowPayInfo.getPayCode(),flowPayInfo.getTradeNo(),flowPayInfo.getRefundCode());
                        if(res.containsKey("errno") && res.get("errno").toString().equals("0")){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }else {
                        flowPayInfo.setRefundCode(CommonUtil.getRanDomStringId());

                        IRefundResult refundResult = payService.refund(0,0,"",flowPayInfo.getPayCode(),flowPayInfo.getRefundCode(),flowPayInfo.getMoneys().doubleValue(),flowPayInfo.getMoneys().doubleValue(),"");
                        System.out.println("refundResult.data().get(\"result_code\")"+refundResult.data().get("result_code"));

                        if(refundResult.status() == 0 && refundResult.data().get("result_code") != null && refundResult.data().get("result_code").equals("SUCCESS")){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            detail.setIsRefund(OrderStatus.IsRefund);
            detail.setPayStatus(OrderStatus.CanselPay);
        }
        //订金退款
        if (!StringUtils.isEmpty(detail.getDepositPayCode())){

            //查询支付的code
            try{
                QueryWrapper<FlowPayInfo> flowPayInfoQueryWrapper = new QueryWrapper<>();
                flowPayInfoQueryWrapper.eq("order_id",detail.getOrderId());
                flowPayInfoQueryWrapper.eq("pay_status",OrderStatus.IsPay);
                flowPayInfoQueryWrapper.eq("pay_code",detail.getDepositPayCode());

                flowPayInfoQueryWrapper.orderByDesc("pay_info_id");

                FlowPayInfo flowPayInfo = flowPayInfoService.getOne(flowPayInfoQueryWrapper);
                if(flowPayInfo != null){
                    System.out.println("tttttttttttt2"+flowPayInfo.getMoneys().intValue());

                    if(flowPayInfo.getPayType().intValue() == 0){
                        //支付宝支付
                        //已经支付
                        AlipayClient client = new AliUtil().getAlipayClient();
                        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
                        refundModel.setOutTradeNo(flowPayInfo.getPayCode());
                        refundModel.setTradeNo(flowPayInfo.getTradeNo());
                        refundModel.setRefundAmount(String .format("%.2f",flowPayInfo.getMoneys().doubleValue()));
                        request.setBizModel(refundModel);
                        AlipayTradeRefundResponse res = client.certificateExecute(request); //发送退款请求,获得退款结果
                        if(res.isSuccess()){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }else if(flowPayInfo.getPayType().intValue() == 1){
                        flowPayInfo.setRefundCode(CommonUtil.getRanDomStringId());
                        Map<String,Object> res = BdUtil.orderRefund(flowPayInfo.getUserId(),flowPayInfo.getPayCode(),flowPayInfo.getTradeNo(),flowPayInfo.getRefundCode());
                        if(res.containsKey("errno") && res.get("errno").toString().equals("0")){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }else {
                        flowPayInfo.setRefundCode(CommonUtil.getRanDomStringId());

                        IRefundResult refundResult = payService.refund(0,0,"",flowPayInfo.getPayCode(),flowPayInfo.getRefundCode(),flowPayInfo.getMoneys().doubleValue(),flowPayInfo.getMoneys().doubleValue(),"");
                        if(refundResult.status() == 0 && refundResult.data().get("result_code") != null && refundResult.data().get("result_code").equals("SUCCESS")){
                            //退款成功
                            flowPayInfo.setIsRefund(OrderStatus.IsRefund);
                            flowPayInfo.setPayStatus(OrderStatus.CanselPay);
                            flowPayInfoService.updateById(flowPayInfo);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            detail.setIsRefund(OrderStatus.IsRefund);
            detail.setPayStatus(OrderStatus.CanselPay);
        }

        detail.setOrderStatus(OrderStatus.OrderCansel);

        boolean result = this.flowOrderService.updateById(detail);
        if(result){
            //更新订单的操作人员
            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
            LoginUser user = LoginContextHolder.getContext().getUser();
            flowOrderParam1.setUpdateUser(user.getId());
            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
            flowOrderService.update(flowOrderParam);
            //查询是否有使用优惠卷，优惠卷退回
            QueryWrapper<FlowOrderDis> flowOrderDisQueryWrapper = new QueryWrapper<>();
            flowOrderDisQueryWrapper.eq("order_id",detail.getOrderId());
            List<FlowOrderDis> flowOrderDis = flowOrderDisService.list(flowOrderDisQueryWrapper);
            if(flowOrderDis.size() != 0){
                //退回优惠卷
                QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
                flowCouponQueryWrapper.eq("coupon_id",flowOrderDis.get(0).getCouponId());
                FlowCoupon flowCoupon = flowCouponService.getOne(flowCouponQueryWrapper);
                if(flowCoupon != null){
                    flowCoupon.setIsUsed(0);
                    flowCouponService.updateById(flowCoupon);
                }
            }
            //取消订单短信
            try{
                QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
                flowServiceQueryWrapper.eq("service_id",detail.getOrderType());
                FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
                //发送支付成功短信
                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
                    flowZfbMemberQueryWrapper.last("limit 1");
                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
                    if(flowZfbMember != null){
                        AliyuncsUtil.sendSmsOrder(5,flowZfbMember.getAccount(),flowService.getServiceName());
                    }
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
                    flowBdMemberQueryWrapper.last("limit 1");
                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
                    if(flowBdMember != null){
                        AliyuncsUtil.sendSmsOrder(5,flowBdMember.getAccount(),flowService.getServiceName());
                    }
                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
                    flowWxMemberQueryWrapper.last("limit 1");
                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
                    if(flowWxMember != null){
                        AliyuncsUtil.sendSmsOrder(5,flowWxMember.getAccount(),flowService.getServiceName());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }else {
            return ResponseData.error("操作失败");
        }
    }

    //服务完成
    @ResponseBody
    @RequestMapping("/serviceSuccess")
    public ResponseData serviceSuccess(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(detail.getOrderStatus() != OrderStatus.OrderWaitService){
            return ResponseData.error("该订单已被处理");
        }
        int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderServiceSuccess,OrderStatus.OrderWaitService);
        if(result > 0){
            //更新订单的操作人员
            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
            LoginUser user = LoginContextHolder.getContext().getUser();
            flowOrderParam1.setUpdateUser(user.getId());
            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
            flowOrderService.update(flowOrderParam1);

            //判断是否上级分销所属订单
            if(!StringUtils.isEmpty(detail.getSuperUserId())){
                Long orderId=detail.getOrderId();
                QueryWrapper<FlowPayInfo> flowPayInfoQueryWrapper = new QueryWrapper<>();
                flowPayInfoQueryWrapper.eq("order_id",orderId);
                flowPayInfoQueryWrapper.eq("pay_status",1);
                flowPayInfoQueryWrapper.last("limit 1");
                List<FlowPayInfo> flowPayInfoList = flowPayInfoService.list(flowPayInfoQueryWrapper);
                BigDecimal moneys=new BigDecimal("0.00");
                for(FlowPayInfo f:flowPayInfoList){
                    moneys=moneys.add(f.getMoneys());
                }
                if(flowPayInfoList.size()==0){
                    moneys=moneys.add(detail.getAllPayMoneys());

//                    moneys=detail.getAllPayMoneys();
                }
//                System.out.println("moneys0:"+moneys);
                Double result1=0.00;
                //获取佣金提成比例
                QueryWrapper<FlowStoreCity> flowStoreCityQueryWrapper = new QueryWrapper<>();
                flowStoreCityQueryWrapper.eq("store_name",detail.getStoreName());
                flowStoreCityQueryWrapper.last("limit 1");
                FlowStoreCity flowStoreCity = flowStoreCityService.getOne(flowStoreCityQueryWrapper);
                if(detail.getOrderType()==1&&!StringUtils.isEmpty(flowStoreCity.getOneAuthorityDiscount())){
                   result1=flowStoreCity.getOneAuthorityDiscount()/100.00;
                    moneys=moneys.multiply(new BigDecimal(result1)).setScale(1,BigDecimal.ROUND_DOWN);
                }else if(detail.getOrderType()==2&&!StringUtils.isEmpty(flowStoreCity.getOneAuthorityCityDiscount())){
                    result1=flowStoreCity.getOneAuthorityCityDiscount()/100.00;
                    moneys=moneys.multiply(new BigDecimal(result1)).setScale(1,BigDecimal.ROUND_DOWN);
                }
                else {
                    QueryWrapper<FlowStoreCity> flowStoreCityQueryWrapper1 = new QueryWrapper<>();
                    flowStoreCityQueryWrapper1.eq("store_name","武汉运营中心");
                    flowStoreCityQueryWrapper1.last("limit 1");
                    FlowStoreCity wuhan = flowStoreCityService.getOne(flowStoreCityQueryWrapper1);
                    if(detail.getOrderType()==1){
                        result1=wuhan.getOneAuthorityDiscount()/100.00;
                        moneys=moneys.multiply(new BigDecimal(result1)).setScale(1,BigDecimal.ROUND_DOWN);
                    }else if(detail.getOrderType()==2){
                        result1=wuhan.getOneAuthorityCityDiscount()/100.00;
                        moneys=moneys.multiply(new BigDecimal(result1)).setScale(1,BigDecimal.ROUND_DOWN);
                    }

                }
//                System.out.println("result1:"+result1);
//                System.out.println("moneys2:"+moneys);

                QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
                flowCommissionManagementQueryWrapper.eq("user_id",detail.getSuperUserId());
                flowCommissionManagementQueryWrapper.eq("only_sign",1l);
                flowCommissionManagementQueryWrapper.last("limit 1");
                FlowCommissionManagement flowCommissionManagement = flowCommissionManagementService.getOne(flowCommissionManagementQueryWrapper);
                if(!StringUtils.isEmpty(flowCommissionManagement.getAllPrice())){
                    flowCommissionManagement.setAllPrice(flowCommissionManagement.getAllPrice().add(moneys));
                }else {
                    flowCommissionManagement.setAllPrice(moneys);

                }

                if(!StringUtils.isEmpty(flowCommissionManagement.getCanDrawPrice())){
                    flowCommissionManagement.setCanDrawPrice(flowCommissionManagement.getCanDrawPrice().add(moneys));

                }else {
                    flowCommissionManagement.setCanDrawPrice(moneys);
                }
                flowCommissionManagementService.updateById(flowCommissionManagement);

                FlowCommissionManagement flowCommissionManagementOrder=new FlowCommissionManagement();
                flowCommissionManagementOrder.setOrderId(detail.getOrderId());
                flowCommissionManagementOrder.setUserId(detail.getSuperUserId().toString());
                flowCommissionManagementOrder.setOneDrawPrice(moneys);
                flowCommissionManagementOrder.setOnlySign(0l);
                flowCommissionManagementService.save(flowCommissionManagementOrder);
                flowOrderParam1.setOneDrawPrice(moneys);
                flowOrderService.update(flowOrderParam1);

                //发送佣金订单完成消息
                WxTemplateUtil wxTemplateUtil=new WxTemplateUtil();
                wxTemplateUtil.send_template_message(detail,detail.getSuperUserId().toString());

            }



            return ResponseData.success("操作成功");
        }else {
            return ResponseData.error("操作失败");
        }
    }

    @ResponseBody
    @RequestMapping("/serviceType")
    public ResponseData serviceType(){
        return ResponseData.success(flowServiceService.list());
    }


    //用户申请退款审核
    @ResponseBody
    @RequestMapping("/refundOrder")
    public ResponseData refundOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(detail.getOrderStatus() != OrderStatus.OrderWaitConfirm){
            return ResponseData.error("该订单已被处理");
        }
        //int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderDealing,OrderStatus.OrderWaitConfirm);
        FlowOrderParam flowOrderParam2 = new FlowOrderParam();
        flowOrderParam2.setRefundStatus(flowOrderParam.getRefundStatus());
        flowOrderParam2.setOrderId(flowOrderParam.getOrderId());
        flowOrderService.update(flowOrderParam2);
        if(flowOrderParam.getRefundStatus() ==1){
            //更新订单的操作人员
//            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
//            LoginUser user = LoginContextHolder.getContext().getUser();
//            flowOrderParam1.setUpdateUser(user.getId());
//            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
//            flowOrderService.update(flowOrderParam1);
            //申请退款
            try{
                QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
                flowServiceQueryWrapper.eq("service_id",detail.getOrderType());
                FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
                //发送支付成功短信
                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
                    flowZfbMemberQueryWrapper.last("limit 1");
                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
                    if(flowZfbMember != null){
                        AliyuncsUtil.sendSmsOrder(3,flowZfbMember.getAccount(),flowService.getServiceName());
                    }
                    this.sendRefundMsg(detail);
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
                    flowBdMemberQueryWrapper.last("limit 1");
                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
                    if(flowBdMember != null){
                        AliyuncsUtil.sendSmsOrder(3,flowBdMember.getAccount(),flowService.getServiceName());
                    }
                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
                    flowWxMemberQueryWrapper.last("limit 1");
                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
                    if(flowWxMember != null){
                        AliyuncsUtil.sendSms(3,flowWxMember.getAccount(),flowService.getServiceName());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }
        else {
            return ResponseData.error("操作失败");
        }

    }

    /**
     * 根据订单查询发送的短信
     * @param flowOrder
     */
    public void sendRefundMsg(FlowOrder flowOrder){
        //查询服务的网点
        try{
            if(flowOrder.getStoreId() == null || flowOrder.getStoreId().intValue() <= 0){
                //查询总公司网点
                QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
                deptQueryWrapper.eq("pid",0);
                deptQueryWrapper.last("limit 1");
                Dept dept = deptService.getOne(deptQueryWrapper);
                if(dept != null){
                    //查询该客服人员
                    QueryWrapper<FlowDeptPhones> flowDeptPhonesQueryWrapper = new QueryWrapper<>();
                    flowDeptPhonesQueryWrapper.eq("dept_id",dept.getDeptId());
                    List<FlowDeptPhones> flowDeptPhones = flowDeptPhonesService.list(flowDeptPhonesQueryWrapper);
                    if(flowDeptPhones.size() > 0){
                        Random random = new Random();
                        int n = random.nextInt(flowDeptPhones.size());
                        AliyuncsUtil.sendSms(6,flowDeptPhones.get(n).getMobile(),flowOrder.getName(),flowOrder.getPhone());
                    }
                }
            }else{
                //查询管理网点的客服电话
                QueryWrapper<FlowDeptPhones> flowDeptPhonesQueryWrapper = new QueryWrapper<>();
                flowDeptPhonesQueryWrapper.apply("dept_id in (select dept_id from flow_dept_store where store_id = "+flowOrder.getStoreId().longValue()+")");
                List<FlowDeptPhones> flowDeptPhones = flowDeptPhonesService.list(flowDeptPhonesQueryWrapper);
                if(flowDeptPhones.size() > 0){
                    Random random = new Random();
                    int n = random.nextInt(flowDeptPhones.size());
                    AliyuncsUtil.sendSms(6,flowDeptPhones.get(n).getMobile(),flowOrder.getName(),flowOrder.getPhone());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


